import { Routes } from "./Routes";

// lofei
//
const { ccclass, property } = cc._decorator;

/**
 * 
 */
@ccclass
export class Player extends cc.Component {
    @property
    mRouteIndex: number = 0;
    @property(cc.Node)
    mRoutes: cc.Node = null;
    @property
    mSpeed: number = 300;
    @property(cc.Label)
    mWord: cc.Label = null;
    _step = 0;
    _walktime = 0;
    _vx = 0;
    _vy = 0;
    _passtime;
    _route = [];
    _isWalking: boolean = false;
    _wordList = [
        "快走！赶着吔屎啦！",
        "前方有屎，冲鸭！",
        "让开，挡着我吃屎了！",
        "衰仔，扑街！",
        "丢雷老母"
    ]
    // LIFE-CYCLE CALLBACKS:

    // onLoad () {}

    start() {
    }

    update(dt) {
        if (this._isWalking) {
            this._passtime += dt;
            if (this._passtime > this._walktime) {
                dt -= (this._passtime - this._walktime);
            }
            let sx = this._vx * dt;
            let sy = this._vy * dt;
            this.node.x += sx;
            this.node.y += sy;

            if (this._passtime >= this._walktime) {
                this._step++;
                this.nextStep();
            }
        }
    }

    run() {
        this.node.active = true;
        this.mSpeed = Math.floor(Math.random() * (300 - 100 + 1) + 100);
        this.say();

        if (!this._route || this._route.length < 1) {
            let routes = this.mRoutes.getComponent(Routes);
            this.mRouteIndex = Math.floor(Math.random() * (1 + 1))
            this._route = routes.getAllRoutesData()[this.mRouteIndex];
        }

        this.node.setPosition(this._route[0].x, this._route[0].y);
        this._step = 1;
        this._isWalking = true;
        this.nextStep();
    }

    say() {
        let len = this._wordList.length;
        let index = Math.floor(Math.random() * (len + 1));
        if (index < 0 || index >= len) {
            index = 0;
        }
        this.mWord.string = this._wordList[index];
    }

    nextStep() {
        if (this._step >= this._route.length) {
            this.node.removeFromParent();
        } else {
            let src = this.node.position;
            let dst = this._route[this._step];
            let dir = dst.sub(src);

            let len = dir.mag();
            this._walktime = len / this.mSpeed;
            this._vx = this.mSpeed * dir.x / len;
            this._vy = this.mSpeed * dir.y / len;
            this._passtime = 0;
        }
    }
}
